package controller

import (
	"blog/entity"
	"blog/service"
	"blog/utils"
	"encoding/json"
	"io"
	"net/http"
	"strconv"
)

/*
将userController注册到http
*/
func init() {
	http.HandleFunc("/blog/user/list", list)
	http.HandleFunc("/blog/user", getUserBayId)
	http.HandleFunc("/blog/user/save", saveUser)
	http.HandleFunc("/blog/user/update", updateUser)
	http.HandleFunc("/blog/user/del", delUser)
	http.HandleFunc("/blog/user/dels", delUsers)
}

/*
获取用户列表
*/
func list(writer http.ResponseWriter, request *http.Request) {
	userList := utils.R(service.GetUserList())

	_, _ = io.WriteString(writer, userList)
}

/*
根据用户id查询用户
*/
func getUserBayId(writer http.ResponseWriter, request *http.Request) {
	query := request.URL.Query()
	id, _ := strconv.Atoi(query.Get("id"))
	user := utils.R(service.GetUserBayID(id))

	_, _ = io.WriteString(writer, user)
}

/*
新增用户
*/
func saveUser(writer http.ResponseWriter, request *http.Request) {
	// 根据请求body创建一个json解析器实例
	decoder := json.NewDecoder(request.Body)
	// 用于存放参数key=value数据
	var user entity.User
	// 解析参数 存入map
	_ = decoder.Decode(&user)
	service.SaveUser(user)

	msg := utils.Rok()

	_, _ = io.WriteString(writer, msg)
}

/*
修改用户信息
*/
func updateUser(writer http.ResponseWriter, request *http.Request) {
	decoder := json.NewDecoder(request.Body)
	var user entity.User
	_ = decoder.Decode(&user)
	service.UpdateUser(user)
	msg := utils.Rok()

	_, _ = io.WriteString(writer, msg)
}

/*
删除用户	逻辑删除
*/
func delUser(writer http.ResponseWriter, request *http.Request) {
	query := request.URL.Query()
	id, _ := strconv.Atoi(query.Get("id"))
	service.DelUserBayId(id)
	msg := utils.Rok()

	_, _ = io.WriteString(writer, msg)
}

/*
批量删除
*/
func delUsers(writer http.ResponseWriter, request *http.Request) {
	query := request.URL.Query()
	ids := query["id"]
	ids2 := make([]int, 10)

	for id := range ids {
		ids2 = append(ids2, id)
	}
	service.DelUserIds(ids2)
	msg := utils.Rok()
	_, _ = io.WriteString(writer, msg)
}
